import 'package:flutter/material.dart';
import 'dlna/dlna.dart';
import 'dlna/xmlParser.dart';

class MediaServerPage extends StatefulWidget {
  final MediaServer server;
  final List<DLNADevice> renderers; // 新增：渲染器列表

  const MediaServerPage({super.key, required this.server, required this.renderers});

  @override
  _MediaServerPageState createState() => _MediaServerPageState();
}

class _MediaServerPageState extends State<MediaServerPage> {
  final List<Map<String, dynamic>> _items = [];
  bool _isLoading = false;
  String? _errorMessage;
  String _currentObjectId = '0'; // 根目录

  @override
  void initState() {
    super.initState();
    _loadContent(_currentObjectId);
  }

  Future<void> _loadContent(String objectId) async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final items = await widget.server.browse(objectId: objectId);
      if (!mounted) return;
      setState(() {
        _items.clear();
        _items.addAll(items);
        _isLoading = false;
        _currentObjectId = objectId;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _errorMessage = '加载内容失败: $e';
      });
    }
  }

  void _playMedia(BuildContext context, Map<String, dynamic> item) {
    if (widget.renderers.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有可用的渲染器')),
      );
      return;
    }

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择渲染器'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: widget.renderers.length,
            itemBuilder: (context, index) {
              final renderer = widget.renderers[index];
              return ListTile(
                leading: const Icon(Icons.cast),
                title: Text(renderer.info.friendlyName),
                onTap: () async {
                  try {
                    final playType = _getPlayType(item['class']);
                    await renderer.setUrl(
                      item['url'],
                      title: item['title'] ?? '未知标题',
                      type: playType,
                    );
                    await renderer.play();
                    if (!mounted) return;
                    Navigator.pop(context);
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('正在 ${renderer.info.friendlyName} 上播放 ${item['title']}'),
                      ),
                    );
                  } catch (e) {
                    if (!mounted) return;
                    Navigator.pop(context);
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('播放失败: $e')),
                    );
                  }
                },
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  PlayType _getPlayType(String? upnpClass) {
    if (upnpClass == null) return PlayType.Video;
    if (upnpClass.contains('video')) return PlayType.Video;
    if (upnpClass.contains('audio')) return PlayType.Audio;
    if (upnpClass.contains('image')) return PlayType.Image;
    return PlayType.Video; // 默认值
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.server.info.friendlyName),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _isLoading ? null : () => _loadContent(_currentObjectId),
            tooltip: '刷新内容',
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 48),
            const SizedBox(height: 10),
            Text(
              _errorMessage!,
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _loadContent(_currentObjectId),
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 10),
            Text('正在加载内容...'),
          ],
        ),
      );
    }

    if (_items.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.folder_open, size: 48, color: Colors.grey),
            SizedBox(height: 10),
            Text('没有可用的媒体内容'),
          ],
        ),
      );
    }

    return ListView.separated(
      itemCount: _items.length,
      separatorBuilder: (context, index) => const Divider(height: 1),
      itemBuilder: (context, index) {
        final item = _items[index];
        final isContainer = item['url'] == null || item['url'].isEmpty;
        return ListTile(
          leading: Icon(isContainer ? Icons.folder : _getMediaIcon(item['class'])),
          title: Text(item['title'] ?? '未知标题'),
          subtitle: Text(isContainer ? '文件夹' : item['url'] ?? ''),
          onTap: () {
            if (isContainer) {
              _loadContent(item['id']); // 导航到子文件夹
            } else {
              _playMedia(context, item); // 播放媒体
            }
          },
        );
      },
    );
  }

  IconData _getMediaIcon(String? upnpClass) {
    if (upnpClass == null) return Icons.insert_drive_file;
    if (upnpClass.contains('video')) return Icons.videocam;
    if (upnpClass.contains('audio')) return Icons.audiotrack;
    if (upnpClass.contains('image')) return Icons.image;
    return Icons.insert_drive_file;
  }
}